import { BadRequestException, ForbiddenException, Injectable, Logger } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { UserService } from "./user.service";
import { CollectEntity } from "src/entity";
import { CollectAddDto, CollectRemoveDto, CollectUpdateDto } from "src/dto/collect";
import { CollectQueryDto } from "src/dto/collect";
import { ConfigService } from "@nestjs/config";
import { pagination } from "src/common/pagination.query";

@Injectable()
export class CollectService {
    private readonly logger = new Logger(CollectService.name);

    constructor(
        @InjectRepository(CollectEntity) private readonly collectRepository: Repository<CollectEntity>,
        private readonly userService: UserService,
        private readonly configService: ConfigService,
    ) {}

    query(id: number, dto: CollectQueryDto) {
        this.logger.log(`requset query user id: ${id} , dto`, dto);

        const qb = this.collectRepository.createQueryBuilder("collect").where("collect.user = :id", { id });
        if (dto.where?.content) {
            qb.andWhere("collect.content LIKE :content", {
                content: `%${dto.where?.content}%`,
            });
        }
        return pagination(qb, dto);
    }

    async add(id: number, collectDto: CollectAddDto) {
        const user = await this.userService.find(id);
        if (!user) {
            throw new ForbiddenException("用户不存在!");
        }

        this.logger.log(`requset add user: ${user.username}`);

        return await this.collectRepository.save(
            this.collectRepository.create({
                ...collectDto,
                user,
            }),
        );
    }

    async update(id: number, collectDto: CollectUpdateDto) {
        this.logger.log(`requset update user id: ${id} collect id: ${collectDto.id}`);
        const result = await this.collectRepository.update(
            {
                id: collectDto.id,
                user: {
                    id,
                },
            },
            collectDto,
        );
        if (result.affected == 0) throw new BadRequestException("更新失败");
    }

    async remove(id: number, collectDto: CollectRemoveDto) {
        this.logger.log(`requset remove user id: ${id} collect id: ${collectDto.id}`);
        const result = await this.collectRepository.delete({
            id: collectDto.id,
            user: {
                id,
            },
        });
        if (result.affected == 0) throw new BadRequestException("删除失败");
    }
}
